package com.itheima.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
@Api(tags = "用户管理")
@RequiredArgsConstructor
public class UserController {

    private final IUserService userService;

    @PostMapping
    @ApiOperation("保存用户")
    public void saveUser(@RequestBody UserFormDTO userFormDTO){
        User user = BeanUtil.copyProperties(userFormDTO, User.class);
        userService.save(user);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除用户")
    public void deleteUser(@PathVariable Long id){
        userService.removeById(id);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询用户")
    public User getUser(@PathVariable Long id){
        return BeanUtil.copyProperties(userService.getById(id), User.class);
    }

    @GetMapping
    @ApiOperation("查询用户列表")
    public List<UserVO> getUserList(UserQuery userQuery){
        // 1.组织条件
        LambdaQueryWrapper<User> queryWrapper = new QueryWrapper<User>().lambda()
                .like(userQuery.getName() != null, User::getUsername, userQuery.getName())
                .eq(userQuery.getStatus() != null, User::getStatus, userQuery.getStatus())
                .ge(userQuery.getMinBalance() != null, User::getBalance, userQuery.getMinBalance())
                .le(userQuery.getMaxBalance() != null, User::getBalance, userQuery.getMaxBalance());

        // 2.查询用户
        List<User> users = userService.list(queryWrapper);
        // 3.处理vo
        return BeanUtil.copyToList(users, UserVO.class);
    }

    @PutMapping("/{id}/deduction/{money}")
    @ApiOperation("修改用户余额")
    public void updateUserBalance(@PathVariable Long id, @PathVariable Integer money){
        userService.updateUserBalance(id,money);
    }

    @GetMapping("/page")
    @ApiOperation("分页查询用户列表")
    public PageDTO<UserVO> queryUsersPage(UserQuery userQuery){
       return userService.queryUsersPage(userQuery);
    }

}
